/**
* Background script of Pixiv Novel Downloader Chrome Extension
* Author: cjls1 2015/05/20
*/

var state = 'open';
var enabled = true;
var cmid = null;

function initState()
{
    state = localStorage['state_title'] ? localStorage['state_title'] : 'open';
    enabled = (state == 'open');
}

function setState(enabled)
{
    localStorage['state_title'] = enabled ? "open" : "close";
    chrome.browserAction.setIcon({
        path : enabled 
            ? "icon_enabled.png" 
            : "icon_disabled.png"});
    chrome.browserAction.setTitle({
        title : enabled 
            ? "Disable Pixiv Novel Downloader" 
            : "Enable Pixiv Novel Downloader"});
}


function myCallback(info, tab) {
    chrome.tabs.sendRequest(tab.id, "getClickedEl", function(clickedEl) {
	//alert(clickedEl.value);
    });
}

function createMenus()
{
    if (cmid == null)
    {
        cmid = chrome.contextMenus.create({
	        'title' : 'Download Pixiv Novel',
	        'contexts' : ['page'],
	        'onclick' : function(info, tab) {
		    if (enabled)
		    {
			myCallback(info, tab);
		    }
	        }
        });
    }
}

function deleteMenus()
{
    chrome.contextMenus.remove(cmid);
    cmid = null;
}

chrome.browserAction.onClicked.addListener(function(tab){
    enabled = !enabled;
    setState(enabled);
});

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.message == 'updateContextMenu') {
        if (request.correcturl && enabled) {
           createMenus();
        }
	else if (cmid != null) {
	    deleteMenus();
        }
    }
    else {
        sendResponse({});
    }
});

initState();
setState(enabled);
